import React, { useState, useRef, useMemo } from 'react';
import {
  Button,
  Table,
  Modal,
  Switch,
  message,
  Space,
  Card,
  Tag,
  Input,
  Form,
  Select,
  FormInstance
} from 'antd';
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  PlusOutlined,
  UserOutlined,
  SearchOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { useUserList, useAddUser, useUpdateUser, useDeleteUser, useUpdateUserState, useRoleList, useRegionList } from '../../../hooks/useUserManagement';
import useSimpleAuth from '../../../hooks/useSimpleAuth';
import './UserList.scss';

const { confirm } = Modal;
const { Option } = Select;

// 定义用户类型，简化字段
interface UserType {
  _id?: string;
  id?: string | number;
  username: string;
  password?: string;
  region?: string;
  roleId?: string | number;
  role?: {
    id?: string | number;
    roleName?: string;
    roleType?: number;
  };
  roleState: boolean;
  default?: boolean;
  seqId?: number;
}

/**
 * 获取用户ID，优先使用MongoDB的_id字段
 */
const getUserId = (user: UserType): string => {
  if (user._id) return user._id.toString();
  if (typeof user.id === 'string' || typeof user.id === 'number') return user.id.toString();
  return user.seqId?.toString() || Math.random().toString();
};

const UserList: React.FC = () => {
  // 状态
  const [isAddVisible, setIsAddVisible] = useState<boolean>(false);
  const [isUpdateVisible, setIsUpdateVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<UserType | null>(null);

  // 表单引用
  const addForm = useRef<FormInstance>(null);
  const updateForm = useRef<FormInstance>(null);
  const searchForm = useRef<FormInstance>(null);

  // 使用钩子获取数据
  const { users, isLoading, handleSearch } = useUserList();
  const { data: roles = [] } = useRoleList();
  const { data: regions = [] } = useRegionList();
  
  // 使用简化版权限钩子
  const { isSuperAdmin, isRegionAdmin, isEditor } = useSimpleAuth();

  // 获取当前用户信息
  const userInfo = useMemo(() => {
    return JSON.parse(localStorage.getItem('userInfo') || '{}');
  }, []);
  
  // 根据部门权限过滤用户列表 - 使用useMemo避免重复计算
  const filteredUsers = useMemo(() => {
    if (!users || !Array.isArray(users)) return [];

    // 超级管理员可以看到所有用户
    if (isSuperAdmin()) {
      return users as UserType[];
    }
    
    // 区域管理员只能看到本区域的编辑用户和自己
    if (isRegionAdmin()) {
      return (users as UserType[]).filter(user => 
        user.username === userInfo.username || // 自己
        (user.region === userInfo.region && 
         (user.role?.roleType === 3 || user.roleId === 3)) // 本区域的编辑
      );
    }
    
    // 编辑只能看到自己
    return (users as UserType[]).filter(user => 
      user.username === userInfo.username
    );
  }, [users, isSuperAdmin, isRegionAdmin, isEditor, userInfo.username, userInfo.region]);

  // 使用钩子进行操作
  const addUserMutation = useAddUser();
  const updateUserMutation = useUpdateUser();
  const deleteUserMutation = useDeleteUser();
  const updateStateMutation = useUpdateUserState();

  // 检查当前用户是否有权限操作指定用户
  const canManageUser = (user: UserType): boolean => {
    if (isSuperAdmin()) return true;
    if (isRegionAdmin()) {
      return user.region === userInfo.region && 
             (user.role?.roleType === 3 || user.roleId === 3);
    }
    if (isEditor()) {
      return user.username === userInfo.username;
    }
    return false;
  };

  // 检查当前用户是否有权限删除指定用户
  const canDeleteUser = (user: UserType): boolean => {
    if (isSuperAdmin()) return !user.default;
    if (isRegionAdmin()) {
      return user.region === userInfo.region && 
             (user.role?.roleType === 3 || user.roleId === 3) &&
             !user.default;
    }
    return false;
  };

  // 表格列定义 - 简化列
  const columns = [
    {
      title: 'ID',
      dataIndex: 'seqId',
      key: 'seqId',
      width: 80,
      render: (seqId: number) => {
        // 处理可能是浮点数的情况
        const displayId = typeof seqId === 'number' ? 
          Math.floor(seqId) : // 如果是数字，去掉小数部分 
          seqId;
        return <Tag color="blue">{displayId}</Tag>;
      },
      sorter: (a: UserType, b: UserType) => {
        // 确保能够正确排序数字类型的seqId
        const aSeq = typeof a.seqId === 'number' ? a.seqId : 0;
        const bSeq = typeof b.seqId === 'number' ? b.seqId : 0;
        return aSeq - bSeq;
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '专业领域',
      dataIndex: 'region',
      key: 'region',
    },
    {
      title: '角色名称',
      key: 'role',
      render: (_: unknown, record: UserType) => {
        const roleId = record.role?.id || record.roleId;
        const roleName = record.role?.roleName ||
          (Array.isArray(roles) ? roles.find(item => item.id === roleId)?.roleName : undefined) || '未知';

        let color = 'default';
        if (roleId === 1) color = 'red';
        else if (roleId === 2) color = 'blue';
        else if (roleId === 3) color = 'green';

        return <Tag color={color}>{roleName}</Tag>;
      }
    },
    {
      title: "用户状态",
      dataIndex: 'roleState',
      key: 'roleState',
      render: (roleState: boolean, record: UserType) => {
        return (
            <Switch
              checked={roleState}
              disabled={record.default || !canManageUser(record)}
              onChange={() => handleStatusChange(record)}
            />
        );
      }
    },
    {
      title: "操作",
      key: 'action',
      render: (_: unknown, record: UserType) => {
        return (
          <Space size="small">
            {canManageUser(record) && (
                <Button 
                  type="primary"
                  icon={<EditOutlined />}
                  disabled={record.default}
                  onClick={() => handleUpdate(record)}
                />
            )}
            
            {canDeleteUser(record) && (
                <Button 
                  type="primary" 
                  danger
                  icon={<DeleteOutlined />}
                  disabled={record.default}
                  onClick={() => confirmDelete(record)}
                />
            )}
          </Space>
        );
      }
    }
  ];

  // 处理用户更新
  const handleUpdate = (record: UserType) => {
    setIsUpdateVisible(true);
    const formData = {
      ...record,
      roleId: record.roleId || record.role?.id || '',
    };
    setCurrent(formData);
    setTimeout(() => {
      updateForm.current?.setFieldsValue(formData);
    }, 0);
  };

  // 处理状态变更
  const handleStatusChange = (record: UserType) => {
    const userId = record._id || record.id;
    if (!userId) {
      message.error('无法更新用户状态：找不到用户ID');
      return;
    }

    updateStateMutation.mutate(
      {
        id: userId,
        roleState: !record.roleState
      },
      {
        onSuccess: () => {
          message.success('用户状态已更改');
        },
        onError: (error) => {
          message.error(`更改状态失败: ${error instanceof Error ? error.message : '未知错误'}`);
        }
      }
    );
  };

  // 确认删除
  const confirmDelete = (record: UserType) => {
    const userId = record._id || record.id;
    if (!userId) {
      message.error('无法删除用户：找不到用户ID');
      return;
    }

    confirm({
      title: '确定删除该用户吗?',
      icon: <ExclamationCircleOutlined />,
      content: '删除后不可恢复.',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        deleteUserMutation.mutate(userId, {
          onSuccess: () => message.success('用户已删除')
        });
      }
    });
  };

  // 添加用户
  const handleAddUser = () => {
    addForm.current?.validateFields().then(async values => {
      if (isRegionAdmin() && values.region !== userInfo.region) {
        message.error('区域管理员只能添加本区域的用户');
        return;
      }

      if (isRegionAdmin() && values.roleId !== 3) {
        message.error('区域管理员只能添加编辑角色的用户');
        return;
      }
      
      // 显示加载状态
      message.loading({ content: '正在添加用户...', key: 'addUser' });
      
      try {
        addUserMutation.mutate(values, {
          onSuccess: () => {
            message.success({ content: '添加用户成功', key: 'addUser' });
            addForm.current?.resetFields();
            setIsAddVisible(false);
          },
          onError: (error) => {
            const errorMsg = error instanceof Error ? error.message : '未知错误';
            message.error({ content: `添加用户失败: ${errorMsg}`, key: 'addUser' });
            console.error('添加用户错误详情:', error);
          }
        });
      } catch (error) {
        message.error({ content: '发生未知错误，请稍后再试', key: 'addUser' });
        console.error('添加用户错误:', error);
      }
    }).catch(formError => {
      message.error('表单数据有误，请检查输入');
      console.error('表单验证错误:', formError);
    });
  };

  // 搜索功能
  const onSearch = () => {
    const formValues = searchForm.current?.getFieldsValue();
    if (formValues) {
      handleSearch(formValues);
    }
  };

  // 重置搜索
  const onReset = () => {
    searchForm.current?.resetFields();
    handleSearch({});
  };

  // 确定当前用户能看到"添加用户"按钮
  const showAddUserButton = isSuperAdmin() || isRegionAdmin();

  return (
    <div className="user-list">
      <Card
        title="用户管理"
        bordered={false}
        extra={
          showAddUserButton && (
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setIsAddVisible(true)}
            >
              添加用户
            </Button>
          )
        }
      >
        {/* 简化搜索表单 */}
        <Form
          layout="inline"
          ref={searchForm}
          style={{ marginBottom: '16px' }}
        >
              <Form.Item name="username" label="用户名">
                <Input placeholder="搜索用户名" prefix={<UserOutlined />} />
              </Form.Item>
          
              <Form.Item>
                <Space>
                  <Button
                    type="primary"
                    icon={<SearchOutlined />}
                    onClick={onSearch}
                  >
                    搜索
                  </Button>
                  <Button
                    icon={<ReloadOutlined />}
                    onClick={onReset}
                  >
                    重置
                  </Button>
                </Space>
              </Form.Item>
        </Form>

        {/* 用户表格 */}
        <Table
          dataSource={filteredUsers}
          columns={columns}
          rowKey={getUserId}
          loading={isLoading}
          pagination={{
            defaultPageSize: 10,
            showTotal: total => `共 ${total} 条记录`
          }}
        />
      </Card>

      {/* 添加用户弹窗 */}
      <Modal
        open={isAddVisible}
        title="添加用户"
        okText="创建"
        cancelText="取消"
        onCancel={() => setIsAddVisible(false)}
        onOk={handleAddUser}
      >
        <Form
          ref={addForm}
          layout="vertical"
          initialValues={{
            roleState: true,
            region: isRegionAdmin() ? userInfo.region : "global",
            roleId: isRegionAdmin() ? 3 : undefined,
          }}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>

          <Form.Item
            name="region"
            label="部门/区域"
            rules={[{ required: true, message: '请选择所属部门' }]}
          >
            <Select 
              placeholder="请选择区域"
              disabled={isRegionAdmin()}
            >
              {Array.isArray(regions) && regions.map(region => (
                <Option key={region.value} value={region.value || ''}>
                    {region.title}
                  </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="roleId"
            label="角色类型"
            rules={[{ required: true, message: '请选择角色类型!' }]}
          >
            <Select 
              placeholder="请选择角色"
              disabled={isRegionAdmin()}
            >
              {Array.isArray(roles) && roles
                .filter(role => isSuperAdmin() || (isRegionAdmin() && role.id === 3))
                .map(role => (
                  <Option key={role.id} value={role.id || ''}>
                    {role.roleName}
                  </Option>
                ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 更新用户对话框 */}
      <Modal
        open={isUpdateVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => setIsUpdateVisible(false)}
        onOk={() => updateForm.current?.validateFields().then(values => {
          if (current) {
            // 权限验证简化
            const userId = current._id || current.id;
            if (userId) {
              updateUserMutation.mutate({
                id: userId,
                data: values
              });
              setIsUpdateVisible(false);
            } else {
              message.error('无法更新用户：找不到用户ID');
            }
          }
        })}
      >
        <Form
          ref={updateForm}
          layout="vertical"
          initialValues={current || {}}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input
              placeholder="请输入用户名"
              disabled={!isSuperAdmin() && current?.username !== userInfo.username}
            />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            tooltip="如不修改密码，请留空"
          >
            <Input.Password placeholder="不修改请留空" />
          </Form.Item>

          <Form.Item
            name="region"
            label="部门/区域"
            rules={[{ required: true, message: '请选择所属部门' }]}
          >
            <Select
              placeholder="请选择区域"
              disabled={!isSuperAdmin()}
            >
              {Array.isArray(regions) && regions.map(region => (
                <Option key={region.value} value={region.value || ''}>
                    {region.title}
                  </Option>
                ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="roleId"
            label="角色类型"
            rules={[{ required: true, message: '请选择角色类型!' }]}
          >
            <Select 
              placeholder="请选择角色"
              disabled={!isSuperAdmin()}
            >
              {Array.isArray(roles) && roles.map(role => (
                <Option key={role.id} value={role.id || ''}>
                    {role.roleName}
                  </Option>
                ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="roleState"
            label="账号状态"
            valuePropName="checked"
          >
            <Switch
              checkedChildren="启用"
              unCheckedChildren="禁用"
              disabled={current?.default || isEditor()}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserList; 